﻿using Common;
using Common.SerializationHelper;
using DeliveryManage.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;


namespace DeliveryManage.Models
{
    public class EmailHandler
    {
        public readonly static EmailHandler Instance = new EmailHandler();
        private EmailHandler()
        { }
        private Queue<EmailQueueInfo> ListQueue = new Queue<EmailQueueInfo>();
        /// <summary>
        /// 加入到处理队列
        /// </summary>
        /// <param name="ToEmail">收件人</param>
        /// <param name="EmailBody">邮件体</param>
        /// <param name="EmailTitle">邮件标题</param>
        public void AddQueue(string ToEmail, string EmailBody, string EmailTitle) //入列
        {
            EmailQueueInfo queueinfo = new EmailQueueInfo();
            queueinfo.EmailTitle = EmailTitle;
            queueinfo.EmailBody = EmailBody;
            queueinfo.ToEmail = ToEmail;
            ListQueue.Enqueue(queueinfo);
        }

        public void Start()//启动
        {
            Thread thread = new Thread(threadStart);
            thread.IsBackground = true;
            thread.Start();
        }

        private void threadStart()
        {
            while (true)
            {
                if (ListQueue.Count > 0)
                {
                    try
                    {
                        ScanQueue();
                    }
                    catch (Exception ex)
                    {
                    }
                }
                else
                {
                    //没有任务，休息200豪秒
                    Thread.Sleep(200);
                }
            }
        }

        //要执行的方法
        private void ScanQueue()
        {
            while (ListQueue.Count > 0)
            {
                try
                {
                    //从队列中取出
                    EmailQueueInfo queueinfo = ListQueue.Dequeue();
                    DeliveryManage.Model.Sys_Config sys = MvcApplication.SysConfig;
                    DTMail.SendEmailSSL(sys.email_host, sys.email_port, sys.email_enable_ssl, sys.email_send_user, sys.email_send_pwd, sys.email_send_username, sys.email_send_adress, queueinfo.ToEmail, queueinfo.EmailTitle, queueinfo.EmailBody);
                }
                catch (Exception ex)
                { }
            }
        }
    }

    //队列临时类
    public class EmailQueueInfo
    {
        public string EmailBody { get; set; }
        public string ToEmail { get; set; }
        public string EmailTitle { get; set; }
    }
}